from datetime import datetime
from django.db.models import Q
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from Oa_system.models import custom_form, application, delegation_table, notification, Staffing
from Oa_system.models import custom_form, application, CompletedProcess
import json, os, time

from administrative.models import Company, ConferenceMemo, Topicsattachments, Topics
from announcements import public_file
from personal_center.models import User, Group, Function
from dateutil.parser import parse
# Create your views here.


# 流程首页
from system_setup.models import punch_clock


class home(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")


        return render(request, "technological/home.html",{'realname': real_name,
                                                               'position': position,
                                                               'department': department})



# 待办流程
class backlog(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")


        return render(request, "technological/backlog.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

    # 返回当前用户待处理流程
    def post(self,request):
        real_name = request.user.real_name
        page = request.POST.get("page", None)           # 页码
        # real_name = '组长'
        to_do_process_obj = application.objects.filter(status=1, present=real_name)
        to_do_process_li = []
        count_num = to_do_process_obj.count()
        for i in to_do_process_obj[(int(page) - 1) * 20:int(page) * 20]:
            item = {}
            item['id'] = i.id
            item['name'] = i.name
            item['form_name'] = i.form_name
            item['department'] = i.department
            item['apply_time'] = i.apply_time
            item['apply_detail'] = i.apply_detail
            item['apply_url'] = i.apply_url
            item['status'] = i.status
            item['form_id'] = i.form_id
            item['present'] = i.present
            to_do_process_li.append(item)

        returnDict= {'code':200, 'message':'success', 'data':to_do_process_li, "count_num": count_num}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 流程权限
class jurisdiction(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")


        return render(request, "technological/jurisdiction.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

# 流程委托
class entrust(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")


        return render(request, "technological/entrust.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

    def post(self,request):
        consignor = request.user.real_name          # 当前账户真实姓名, 委托人
        form_name = request.POST.get("form_name", None)         # 委托流程名称
        formid = request.POST.get("form_id", None)         # 对应表单ID
        flowid = request.POST.get("flow_id", None)         # 对应流程ID
        mandatary = request.POST.get("mandatary", None)         # 被委托人
        create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())          # 委托时间
        look_check = "0"
        delegation_table.objects.create(consignor=consignor, form_name=form_name, formid=formid, flowid=flowid, mandatary=mandatary, create_time=create_time, look_check=look_check)
        CompletedProcess.objects.create(application_id=flowid, user_name=request.user.username, real_name=request.user.real_name, status=3)
        source_dict = json.loads(application.objects.get(id=flowid).flow_status)
        source_dict[consignor] = {'status': '委托', 'opinion': mandatary}
        my_keys = list(source_dict.keys())
        k, v = mandatary, {'status': '未操作', 'opinion': ''}
        my_keys.insert(my_keys.index(consignor) + 1, k)
        source_dict[k] = v
        new_dict = {}
        for k in my_keys:
            new_dict.update({k: source_dict[k]})

        obj = application.objects.get(id=flowid)
        obj.flow_status = json.dumps(new_dict)
        obj.present = mandatary
        obj.save()
        returnDict = {"code": 200, "status": "success", "data": []}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 超时统计
class timeout(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")


        return render(request, "technological/timeout.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

# 已办流程
class already(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")


        return render(request, "technological/already.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

    # 已办流程列表
    def post(self,request):
        username = request.user.username
        page = request.POST.get("page", '1')  # 页码
        already_li = []
        completed_obj = CompletedProcess.objects.filter(user_name=username)
        count_num = completed_obj.count()
        for i in completed_obj[(int(page) - 1) * 20:int(page) * 20]:
            item = {}
            application_id = i.application_id
            item['status'] = i.status
            try:
                j = application.objects.filter(id=application_id)[0]
                item["id"] = j.id
                item['name'] = j.name
                item['form_name'] = j.form_name
                item['department'] = j.department
                item['apply_time'] = j.apply_time
                item['apply_detail'] = j.apply_detail
                item['apply_url'] = j.apply_url
                item['form_id'] = j.form_id
                item['present'] = j.present
                item['flow_status'] = j.flow_status
                already_li.append(item)
            except Exception as e:
                print(f'application_id:{application_id},error:{e}')
                item["id"] = ""
                item['name'] = ''
                item['form_name'] = ''
                item['department'] = ''
                item['apply_time'] = ''
                item['apply_detail'] = ''
                item['apply_url'] = ''
                item['form_id'] = ''
                item['present'] = ''
                item['flow_status'] = ''
            # already_li.append(item)
        returnDict = {'code': 200, 'message': 'success', 'data': already_li, "count_num": count_num}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 知会流程
class notify(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")


        return render(request, "technological/notify.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

# 我的申请
class apply(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")


        return render(request, "technological/apply.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

    def post(self, request):
        returnDict, return_list = {}, []
        user_id = request.session.get("_auth_user_id")
        page = request.POST.get("page", None)               # 页码
        one_data = User.objects.get(id=user_id)
        real_name = one_data.real_name

        all_data = application.objects.filter(name=real_name)           # 获取当前账户所有的申请流程
        count_num = all_data.count()
        for dat in all_data[(int(page) - 1) * 20:int(page) * 20]:
            status = dat.status
            if status == "1":
                status = "审批中"
            elif status == "2":
                status = "驳回"
            elif status == "3":
                status = "审批通过"
            elif status == "4":
                status = "撤回"
            else:
                status = "驳回"

            one_dict = {}
            one_dict["id"] = dat.id
            one_dict["form_id"] = dat.form_id
            one_dict["form_name"] = dat.form_name           # 流程名称
            one_dict["apply_time"] = dat.apply_time             # 申请时间
            one_dict["status"] = status                 # 流程状态
            one_dict["present"]=  dat.present           # 当前节点
            return_list.append(one_dict)
        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["count_num"] = count_num
        returnDict["data"] = return_list
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 流程设置
class workflow_setting(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        category_data = custom_form.objects.values("category").distinct()
        category_list = []
        for i in category_data:
            category_list.append(i["category"])


        return render(request, "technological/workflow_setting.html", {"category_list": category_list,
                                                                       'realname': real_name,
                                                                        'position': position,
                                                                        'department': department
                                                                       })

    def post(self, request):
        returnDict = {}
        flowStr = request.POST.get("flowStr", None)         # 流程图
        TableJson = request.POST.get("TableJson", None)         # 自定义表单
        regimentation = request.POST.get("regimentation", None) # 流程类别
        table_name = request.POST.get("table_name", None)           # 表单名称
        if flowStr and TableJson and regimentation and table_name:
            custom_form.objects.create(name=table_name, form_html=TableJson, flow=flowStr, category=regimentation.strip())
            returnDict["code"] = 200
            returnDict["status"] = "success"
            returnDict["data"] = []

        else:
            returnDict["code"] = 400
            returnDict["status"] = "err"
            returnDict["data"] = ["参数不全"]

        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 流程设置列表
class workflow_table(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        return render(request, "technological/workflow_table.html",{'realname': real_name,
                                                            'position': position,
                                                            'department': department})

    def post(self, request):
        alldata = custom_form.objects.filter(is_del=False)  # 查询所有数据
        returnDict, table_data = {}, []
        page = request.POST.get("page", None)           # 页码
        # 构建json数据返回前端
        count_num = alldata.count()
        for dat in alldata[(int(page) - 1) * 20:int(page) * 20]:
            one_dict = {}
            one_dict["id"] = dat.id
            one_dict["category"] = dat.category
            one_dict["name"] = dat.name
            table_data.append(one_dict)

        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["count_num"] = count_num
        returnDict["data"] = table_data
        return HttpResponse(json.dumps(returnDict), content_type="application/json")



class DelWorkFlowTable(View):
    def get(self, request):
        pass
    def post(self, request):
        page = request.POST.get("page", None)           # 页码
        table_id = request.POST.get("id", None)           # 页码
        print('page:',page)
        print('table_id:',table_id)
        if not table_id:
            returnDict = {
                'code':400,
                'status':'缺少必传参数',
                'count_num':0,
                'data':[]
            }
            print(returnDict)
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict, table_data = {}, []
        try:
            del_obj = custom_form.objects.get(id=table_id)
            del_obj.is_del = True
            del_obj.save()
        except:
            returnDict["code"] = 400
            returnDict["status"] = "删除失败"


        alldata = custom_form.objects.filter(is_del=False)  # 查询所有数据
        # 构建json数据返回前端
        count_num = alldata.count()
        for dat in alldata[(int(page) - 1) * 20:int(page) * 20]:
            one_dict = {}
            one_dict["id"] = dat.id
            one_dict["category"] = dat.category
            one_dict["name"] = dat.name
            table_data.append(one_dict)

        if 'code' not in returnDict.keys():
            returnDict["code"] = 200
            returnDict["status"] = "success"
        returnDict["count_num"] = count_num
        returnDict["data"] = table_data

        return HttpResponse(json.dumps(returnDict), content_type="application/json")





# 流程申请
class apply_detail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        flowId = request.GET.get("flowId", None)            # 流程ID
        application_id = request.GET.get("application_id", None)            # 流程ID
        all_data = custom_form.objects.get(id=flowId)
        # for dat in all_data:
        form_data = all_data.form_html
        flow_table = all_data.flow
        form_name = all_data.name
        user_id = request.session.get("_auth_user_id")
        one_data = User.objects.get(id=user_id)


        return render(request, "technological/apply_detail.html", {"jsondata": flow_table, "form_data": form_data, "form_name": form_name, "real_name": one_data.real_name, "department": one_data.department,
                                                                   'realname': real_name,
                                                                    'position': position})


# 上传附件
class upload_accessory(View):
    def post(self, request):
        returnDict = {}
        file_path = os.path.join(os.getcwd(), 'static/announcements/UploadAccessory')
        myFiles = request.FILES.get("file", None)
        if not os.path.exists(file_path):
            os.mkdir(file_path)

        with open(os.path.join(file_path, myFiles.name), "wb") as F:
            for i in myFiles.chunks():
                F.write(i)
        accessory_dict = {}
        accessory_dict["accessory_url"] = f"static/announcements/UploadAccessory/{myFiles.name}"
        accessory_dict["accessory_name"] = myFiles.name
        accessory_dict["upload_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        accessory_dict["file_size"] = public_file.StrOfSize(myFiles.size)
        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["data"] = [accessory_dict]
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 流程撤回
class revocation(View):
    def post(self, request):
        returnDict, return_list = {}, []
        user_id = request.session.get("_auth_user_id")
        page = request.POST.get("page", None)  # 页码
        meeting_type = request.POST.get("type", None)
        one_data = User.objects.get(id=user_id)
        real_name = one_data.real_name
        revocation_id = request.POST.get("revocation_id", None)             # 撤回流程ID
        if revocation_id:
            obj = application.objects.get(id=revocation_id)
            obj.status = "4"
            obj.save()
        if meeting_type:
            all_data = application.objects.filter(name=real_name, form_name="会议申请")
        else:
            all_data = application.objects.filter(name=real_name)  # 获取当前账户所有的申请流程
        count_num = all_data.count()
        for dat in all_data[(int(page) - 1) * 20:int(page) * 20]:
            status = dat.status
            if status == "1":
                status = "审批中"
            elif status == "2":
                status = "驳回"
            elif status == "3":
                status = "审批通过"
            elif status == "4":
                status = "撤回"
            else:
                status = "驳回"

            one_dict = {}
            one_dict["id"] = dat.id
            one_dict["form_id"] = dat.form_id
            one_dict["form_name"] = dat.form_name  # 流程名称
            one_dict["apply_time"] = dat.apply_time  # 申请时间
            one_dict["status"] = status  # 流程状态
            one_dict["present"] = dat.present  # 当前节点
            return_list.append(one_dict)
        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["count_num"] = count_num
        returnDict["data"] = return_list
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 审批意见处理
class ParseFlow(View):
    def get(self,request):
        pass
    def post(self,request):
        real_name = request.user.real_name
        status = request.POST.get('status') # 状态
        application_id = request.POST.get('application_id') # 申请表的id
        approval_opinion = request.POST.get('approval_opinion') # 审批意见
        trust = request.POST.get("trust", None)             # 判断是否是委托
        if not all([status,application_id]):
            returnDict = {'code': 200, 'message': '缺少必传参数'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if status not in ['2','3']:
            returnDict = {'code': 200, 'message': 'status错误，只能选数字2或3, 其中2:驳回,3:审批通过'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        # 修改状态
        try:
            application_obj = application.objects.filter(id=application_id,present=real_name)[0]
        except:
            returnDict = {'code': 400, 'message': '操作失败'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        application_obj.status = status #
        flow_status_str = application_obj.flow_status
        flow_status_json_dict = json.loads(flow_status_str)
        flow_status_json_dict[real_name]['status'] = '驳回' if status == '2' else '通过'
        flow_status_json_dict[real_name]['opinion'] = approval_opinion
        application_obj.flow_status = json.dumps(flow_status_json_dict)
        application_obj.save()
        # 获取流程列表
        apply_detail = json.loads(application_obj.flow_status)

        name_li = list(apply_detail.keys())

        CompletedProcess.objects.create(
            application_id=application_obj.id,
            user_name=request.user.username,
            real_name=request.user.real_name,
            status=status
        )

        # # 修改委托状态
        if trust:
            print(trust)
            obj = delegation_table.objects.get(id=trust)
            obj.look_check = 1
            obj.save()

        # 驳回的处理
        if status == '2':
            application_obj.present = application_obj.name
            application_obj.status = '2'
            application_obj.save()
        # 通过的处理
        elif status == '3':
            now_index = name_li.index(real_name)
            if now_index + 1 < len(name_li):
                next_name = name_li[now_index + 1]
                application_obj.present = next_name  # 修改成下一个处理人
                application_obj.status = '1'  # 状态变成1
                application_obj.save()
            else:
                application_obj.present = application_obj.name  # 修改成申请人
                application_obj.status = '3'  # 状态变成1
                application_obj.save()

        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")



# 流程审批
class approve(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        formId = request.GET.get("form_id", None)  # 表单ID
        flowId = request.GET.get("flow_id", None)  # 流程ID
        all_data = custom_form.objects.get(id=formId)
        form_data = all_data.form_html
        flow_table = all_data.flow
        one_data= application.objects.get(id=flowId)          #.apply_detail
        form_detail = one_data.apply_detail


        return render(request, "technological/approve.html", {"form_data": form_data, "form_detail": form_detail,
                                                              'realname': real_name,
                                                            'position': position,
                                                            'department': department})


# 创建委托弹框
class delegation(View):
    def post(self, request):
        returnDict, return_list, department_list = {}, [], []
        branch_list = [{'department': com.name, 'id': com.id} for com in Company.objects.filter(~Q(id=87)).order_by('serial_number')]
        group_list = []
        one_dict = {}
        emp_info_dict = {}
        people_dict_new = {}
        function_dict_new = {}
        groups = Group.objects.all()
        functions = Function.objects.all()
        function_dict = {}
        for group in groups:
            # group_list.append(group.level)
            people_dict_new[group.level] = [{'real_name': user_objs.real_name, 'job_number': user_objs.job_number} for
                                            user_objs in group.user_set.all() if (user_objs.job_number not in ['0000', '8888'] and user_objs.is_delete==0)]

        people_dict_new['B'] =  [{'real_name': user_objs.real_name, 'job_number': user_objs.job_number} for
                                            user_objs in Staffing.objects.get(station='院领导').post_personnel.all()]

        people_dict_new['B'] = [{'real_name': user_objs.real_name, 'job_number': user_objs.job_number} for
                                user_objs in Staffing.objects.get(station='院领导').post_personnel.all()]

        for function in functions:
            function_dict[function.describe] = function.packet
            function_dict_new[function.packet] = [{'real_name': user_objs.real_name, 'job_number': user_objs.job_number} for
                                            user_objs in function.function_ids_users.all()]


        function_dict_new["function_dict"] = function_dict

        for i in branch_list:
            # if i["department"]:
            if i['department'] not in return_list:
                return_list.append(i['department'])
            one_data = User.objects.filter(company_id=i['id'], is_delete='0')
            real_name_list = []
            emp_info = []
            for dat in one_data:
                real_name_list.append(dat.real_name)
                emp_info.append({
                    'real_name': dat.real_name,
                    'job_number': dat.job_number
                })
            if i['department'] in one_dict:
                one_dict[i['department']] += real_name_list
                emp_info_dict[i['department']] += emp_info
            else:
                one_dict[i['department']] = real_name_list
                emp_info_dict[i['department']] = emp_info

        returnDict["code"] = 200
        returnDict["status"] = "success"
        returnDict["data"] = one_dict
        returnDict["emp_info_dict"] = emp_info_dict
        returnDict["people_dict_new"] = people_dict_new
        returnDict["branch_list"] = return_list
        returnDict["function_list"] = function_dict_new
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 获取委托列表
class trust(View):
    def post(self, request):
        returnDict = {}
        page = request.POST.get("page", None)           # 页码
        mandatary = request.user.real_name
        all_data = delegation_table.objects.filter(mandatary=mandatary, look_check=0)
        returnList = []
        count_num = all_data.count()                # 总数据量
        for dat in all_data[(int(page) - 1) * 20:int(page) * 20]:
            one_dict = {}
            one_dict["id"] = dat.id
            one_dict["flowId"] = dat.flowid
            one_dict["formId"] = dat.formid
            one_dict["form_name"] = dat.form_name
            one_dict["consignor"] = dat.consignor
            one_dict["mandatary"] = dat.mandatary
            one_dict["create_time"] = dat.create_time
            returnList.append(one_dict)
        returnDict["code"] = 200
        returnDict["count_num"] = count_num
        returnDict["status"] = "success"
        returnDict["data"] = returnList
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class View_has(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        formId = request.GET.get("form_id", None)  # 表单ID
        flowId = request.GET.get("flow_id", None)  # 流程ID
        all_data = custom_form.objects.get(id=formId)
        form_data = all_data.form_html
        flow_table = all_data.flow
        one_data = application.objects.get(id=flowId)  # .apply_detail
        form_detail = one_data.apply_detail

        present = one_data.flow_status
        status = one_data.status
        if status == "1":
            img_name = "approve.png"
        elif status == "2":
            img_name = "nopass.png"
        elif status == "3":
            img_name = "pass.png"
        elif status == "4":
            img_name = "撤回.png"
        else:
            img_name = "驳回.png"


        return render(request, "technological/View_has.html",
                      {"jsondata": flow_table, "form_data": form_data, "form_detail": form_detail, "img_name": img_name,
                       "present": present, 'realname': real_name,
                                                            'position': position,
                                                            'department': department})



class ApplicantNoticeView(View):
    # 获取流程结束后未读的流程
    def get(self, request):
        real_name = request.user.real_name
        page = request.GET.get('page','1')
        application_obj = application.objects.filter(name=real_name,present=real_name,is_read=False)
        count_num = application_obj.count()
        data_li = []
        for dat in application_obj[(int(page) - 1) * 20:int(page) * 20]:
            item = {}
            item['application_id'] = dat.id
            item['name'] = dat.name
            item['form_name'] = dat.form_name
            item['department'] = dat.department
            item['apply_time'] = dat.apply_time
            item['apply_detail'] = dat.apply_detail
            item['apply_url'] = dat.apply_url
            item['status'] = dat.status
            item['form_id'] = dat.form_id
            item['present'] = dat.present
            item['flow_status'] = dat.flow_status
            data_li.append(item)
        returnDict = {'code': 200, 'message': 'success', 'data': data_li, "count_num": count_num}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


    # 修改用户已读
    def post(self, request):
        application_id = request.POST.get('application_id',None)
        if not application_id:
            returnDict = {'code': 400, 'message': '缺少必传参数'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        real_name = request.user.real_name
        application_obj = application.objects.filter(id=application_id, present=real_name, is_read=False)
        for i in application_obj:
            i.is_read = True
            i.save()
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")



# 考勤打卡
class PunchClock(View):
    def post(self, request):
        this_id = request.POST.get("this_id", None)
        time_id = request.POST.get("time_id", None)
        clock_time = request.POST.get("clock_time", None)
        types, off_work_time, go_work_time = "b", time_id, ""

        if this_id == "clock_in":
            types = "a"
            go_work_time = time_id
            off_work_time = ""

        try:
            clock_obj = punch_clock.objects.get(clock_people=request.user, clock_time=clock_time)
            if go_work_time:
                clock_obj.go_work_time=go_work_time
            if off_work_time:
                clock_obj.off_work_time=off_work_time
            clock_obj.save()
        except:
            punch_clock.objects.create(
                state=types,
                clock_people=request.user,
                go_work_time=go_work_time,
                off_work_time=off_work_time,
                clock_time=clock_time
            )
        returnDict = {'code': 200, 'message': 'success', "data": "打卡成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class UploadContract(View):
    def post(self, request):
        myfile = request.FILES.get('files')

        SuffixName = os.path.splitext(myfile.name)[-1]
        print(SuffixName)
        if SuffixName not in [".pdf", ".PDF"]:
            returnDict = {'code': 400, 'message': 'success', "data": "请上传PDF文件！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        file_path = os.getcwd() + "/media/contract_file/" + myfile.name
        if os.path.exists(file_path):
            os.remove(file_path)

        with open(file_path, 'wb') as fp:
            for chunk in myfile.chunks():
                fp.write(chunk)

        returnDict = {'code': 200, 'message': 'success', "data": {"file_path": file_path.replace(os.getcwd(), "")}}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SearchSummary(View):
    def post(self, request):
        FillInMinutes = request.POST.get('FillInMinutes', "")
        conf_obj = ConferenceMemo.objects.filter(Q(conference_memo_text__contains=FillInMinutes), type='b', state="seven")
        conf_dict = []
        for i in conf_obj:
            conference_memo_text = i.conference_memo_text
            TopicObj = Topicsattachments.objects.filter(topics_number=i.number)
            if TopicObj.filter(file_type="1"):
                file_path = TopicObj.filter(file_type="1").first().pdf_path
                file_id = TopicObj.filter(file_type="1").first().id
            else:
                file_path = TopicObj.first().pdf_path
                file_id = TopicObj.first().id
            conf_dict.append({"title": conference_memo_text, "file_path": file_path, "file_id": file_id})
        returnDict = {'code': 200, 'message': 'success', "data": conf_dict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SearchTopics(View):
    def post(self, request):
        year_number_list = request.POST.get('year_number_list', "")
        FillInTopic = request.POST.get('FillInTopic', "")
        if year_number_list:
            year_number_list = json.loads(year_number_list)
            topic_obj = Topics.objects.filter(Q(topics_name__contains=FillInTopic), iss_year=year_number_list[0], meetings_num=year_number_list[1], type='yb', state__in=["unmetting", "metting", "done"])
            conf_dict = []
            for i in topic_obj:
                conf_dict.append({"id": i.id, "title": i.topics_name})
            returnDict = {'code': 200, 'message': 'success', "data": conf_dict}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'code': 200, 'message': 'success', "data": []}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class LeaveReport(View):
    def post(self, request):
        rsk_obj = Company.objects.get(id=16).head_people
        flag = 'flase'
        if request.user == rsk_obj:
            flag = 'true'
        returnDict = {'code': 200, 'message': 'success', "flag": flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SalaryAuthority(View):
    def post(self, request):
        jgb_obj = Company.objects.get(id=10).head_people
        flag = 'flase'
        if request.user == jgb_obj:
            flag = 'true'
        returnDict = {'code': 200, 'message': 'success', "flag": flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class NavigationQuery(View):
    def post(self, request):
        Navigation_type = request.POST.get("Navigation_type", '1')
        if Navigation_type == '1':
            CompanyObj = Company.objects.all().order_by("serial_number")
            objs = []
            for obj in range(len(CompanyObj)):
                flag = 'true' if obj == 0 else "flase"
                objs.append({'id': CompanyObj[obj].id, 'name': CompanyObj[obj].name, 'flag': flag})
            people_list = []
            peo_obj = User.objects.filter(company__id=3, is_delete=0)
            for peo in peo_obj:
                people_list.append({'id': peo.id, 'real_name': peo.real_name, 'job_number': peo.job_number})
        elif Navigation_type == '2':
            group_dict = {'A': '书记、院长', "B": '院领导', "C": '职能科室负责人', "D": '临床医技科室负责人', "G": "副主任", "E": "护士长", "F": '普通员工'}
            groups = Group.objects.all().order_by("create_time")
            objs = []
            for obj in range(len(groups)):
                flag = 'true' if obj == 0 else "flase"
                objs.append({'id': groups[obj].id, 'name': group_dict[groups[obj].level], 'flag': flag})

            people_list = []
            peo_obj = User.objects.filter(group__id=groups.first().id, is_delete=0)
            for peo in peo_obj:
                people_list.append({'id': peo.id, 'real_name': peo.real_name, 'job_number': peo.job_number})
        else:
            functions = Function.objects.all()
            objs = []
            for obj in range(len(functions)):
                flag = 'true' if obj == 0 else "flase"
                objs.append({'id': functions[obj].id, 'name': functions[obj].describe, 'flag': flag})
            people_list = []
            peo_obj = functions.first().function_ids_users.all()
            for peo in peo_obj:
                people_list.append({'id': peo.id, 'real_name': peo.real_name, 'job_number': peo.job_number})
        returnDict = {'code': 200, 'message': 'success', "objs": objs, 'people_list': people_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SecondaryNavigation(View):
    def post(self, request):
        curr_id = request.POST.get("curr_id", 1)
        OneNavigation = request.POST.get("OneNavigation", 1)
        people_list = []
        print("=============", OneNavigation, curr_id)
        if OneNavigation == 'dep':
            if int(curr_id) != 3:
                peo_obj = User.objects.filter(~Q(id__in=[2, 3]), company__id=int(curr_id), is_delete=0)
            else:
                peo_obj = User.objects.filter(~Q(id__in=[2, 3]), company__id__in=[3, 80], is_delete=0)
            for peo in peo_obj:
                people_list.append({'id': peo.id, 'real_name': peo.real_name, 'job_number': peo.job_number})
        elif OneNavigation == 'limits':
            if int(curr_id) == 3:
                functional_obj = Company.objects.filter(is_functional=1)
                peo_obj = []
                for iss in functional_obj:
                    peo_obj.append(iss.head_people)
            elif int(curr_id) == 4:
                functional_obj = Company.objects.filter(is_functional=0)
                peo_obj = []
                for noo in functional_obj:
                    peo_obj.append(noo.head_people)
            else:
                peo_obj = User.objects.filter(~Q(id__in=[2, 3]), group__id=int(curr_id), is_delete=0)
            for peo in peo_obj:
                if peo:
                    people_list.append({'id': peo.id, 'real_name': peo.real_name, 'job_number': peo.job_number})
        else:
            peo_obj = Function.objects.filter(id=int(curr_id)).first().function_ids_users.all()
            for peo in peo_obj:
                people_list.append({'id': peo.id, 'real_name': peo.real_name, 'job_number': peo.job_number})
        returnDict = {'code': 200, 'message': 'success', 'people_list': people_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SearchDepartment(View):
    def post(self, request):
        search_value = request.POST.get("search_value", '')
        CompanyObj = Company.objects.filter(name__contains=search_value)
        objs = []
        for obj in range(len(CompanyObj)):
            flag = 'true' if obj == 0 else "flase"
            objs.append({'id': CompanyObj[obj].id, 'name': CompanyObj[obj].name, 'flag': flag})
        people_list = []
        peo_obj = User.objects.filter(company__id=CompanyObj.first().id)
        for peo in peo_obj:
            people_list.append({'id': peo.id, 'real_name': peo.real_name, 'job_number': peo.job_number})
        returnDict = {'code': 200, 'message': 'success', "objs": objs, 'people_list': people_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SearchPersonnel(View):
    def post(self, request):
        search_value = request.POST.get("search_value", '')
        Dep_value = request.POST.get("Dep_value", '')
        people_list = []
        print(Dep_value, search_value)
        if Dep_value:
            peo_obj = User.objects.filter(~Q(id__in=[2, 3]), real_name__contains=search_value, company__name__contains=Dep_value, is_delete=0)
        else:
            peo_obj = User.objects.filter(~Q(id__in=[2, 3]), real_name__contains=search_value, is_delete=0)
        for peo in peo_obj:
            people_list.append({'id': peo.id, 'real_name': peo.real_name, 'job_number': peo.job_number})
        returnDict = {'code': 200, 'message': 'success', 'people_list': people_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")